package com.example.demo.controller;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.annotation.Lock4j;
import com.example.demo.executor.RedissonLockNewExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 分享一个分布式锁框架Lock4j
 * 基于Spring AOP的声明式和编程式分布式锁，支持RedisTemplate、Redisson、Zookeeper。
 */
@RestController
@RequestMapping("/mock")
public class MockController {

    @GetMapping("/lockMethod")
    @Lock4j(keys = {"#key"}, acquireTimeout = 10, expire = 10000
            ,executor = RedissonLockNewExecutor.class
    )
    public String lockMethod(@RequestParam String key) throws InterruptedException {
        Thread.sleep(10000);
        return key;
    }

    @Autowired
    private LockTemplate lockTemplate;

    @GetMapping("/lockMethodCostom")
    public String lockMethodCostom(@RequestParam String key) {
        LockInfo lock = lockTemplate.lock(key, 10000L, 2000L, RedissonLockNewExecutor.class);
        if (lock == null) {
            // 获取不到锁
            throw new RuntimeException("业务处理中，请稍后再试...");
        }
        // 获取锁成功，处理业务
        try {
            doBusiness();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lockTemplate.releaseLock(lock);
        }
        return key;
    }

    private void doBusiness() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("woniuhaobang");
    }


}
